﻿@model ShipmentListModel
@inject AdminAreaSettings adminAreaSettings
@{
    //page title
    ViewBag.Title = T("Admin.Orders.Shipments.List").Text;
}

<form asp-controller="Shipment" asp-action="List" method="post">
    
    <div class="row">
        <div class="col-md-12">
            <div class="x_panel light form-fit">
                <div class="x_title">
                    <div class="caption">
                        <i class="fa fa-truck"></i>
                        @T("Admin.Orders.Shipments.List")
                    </div>
                    <div class="actions">
                        <div class="btn-group btn-group-devided util-btn-margin-bottom-5">
                            <button type="submit" name="exportpackagingslips-all" class="btn purple">
                                <i class="fa fa-file-pdf-o"></i>
                                @T("Admin.Orders.Shipments.PrintPackagingSlip.All")
                            </button>
                            <button type="submit" id="exportpackagingslips-selected" class="btn blue">
                                <i class="fa fa-file-pdf-o"></i>
                                @T("Admin.Orders.Shipments.PrintPackagingSlip.Selected")
                            </button>
                            <button class="btn btn-success" type="submit" id="ship-selected"><i class="fa fa-check"></i> @T("Admin.Orders.Shipments.ShipSelected") </button>
                            <button class="btn btn-success" type="submit" id="deliver-selected"><i class="fa fa-check-circle"></i> @T("Admin.Orders.Shipments.DeliverySelected") </button>
                            <vc:admin-widget widget-zone="order_shipment_list_buttons" additional-data="null" />
                        </div>
                    </div>
                </div>
                <div class="x_content form">
                    <div class="form-horizontal">
                        <div class="form-body">
                            <div class="form-group">
                                <admin-label asp-for="StartDate" />
                                <div class="col-md-9 col-sm-9">
                                    <admin-input asp-for="StartDate" />
                                </div>
                            </div>
                            <div class="form-group">
                                <admin-label asp-for="EndDate" />
                                <div class="col-md-9 col-sm-9">
                                    <admin-input asp-for="EndDate" />
                                </div>
                            </div>
                            <div class="form-group">
                                <admin-label asp-for="TrackingNumber" />
                                <div class="col-md-9 col-sm-9">
                                    <admin-input asp-for="TrackingNumber" />
                                </div>
                            </div>
                            <div class="form-group">
                                <admin-label asp-for="LoadNotShipped" />
                                <div class="col-md-9 col-sm-9">
                                    <label class="mt-checkbox mt-checkbox-outline control control-checkbox">
                                        <admin-input asp-for="LoadNotShipped" />
                                         <div class="control__indicator"></div>
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions">
                            <div class="row">
                                <div class="col-md-offset-3 col-sm-offset-3 col-md-9 col-sm-9">
                                    <button class="btn btn-success filter-submit" id="search-shipments">
                                        <i class="fa fa-search"></i> @T("Admin.Common.Search")
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="x_content">
                            <div id="shipments-grid"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function () {
            $("#shipments-grid").kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                            url: "@Html.Raw(Url.Action("ShipmentListSelect", "Shipment"))",
                            type: "POST",
                            dataType: "json",
                            data: additionalData
                        }
                    },
                    schema: {
                        data: "Data",
                        total: "Total",
                        errors: "Errors"
                    },
                    error: function(e) {
                        display_kendoui_grid_error(e);
                        // Cancel the changes
                        this.cancelChanges();
                    },
                    pageSize: @(adminAreaSettings.DefaultGridPageSize),
                    serverPaging: true,
                    serverFiltering: true,
                    serverSorting: true
                },
                pageable: {
                    refresh: true,
                    pageSizes: [@(adminAreaSettings.GridPageSizes)]
                },
                //details grid
                detailInit: detailInit,
                scrollable: false,
                dataBound: onDataBound,
                columns: [{
                    field: "Id",
                    headerTemplate: "<label class='mt-checkbox mt-checkbox-outline control control-checkbox'><input id='mastercheckbox' type='checkbox'/> <div class='control__indicator'></div></label>",
                    template: "<label class='mt-checkbox mt-checkbox-outline control control-checkbox'><input type='checkbox' value='#=Id#' class='checkboxGroups'/> <div class='control__indicator'></div></label>",
                    width: 40
                }, {
                    field: "ShipmentNumber",
                    title: "@T("Admin.Orders.Shipments.ID")",
                    width: 100,
                    template: '<a class="k-link" href="@Url.Content("~/Admin/Shipment/ShipmentDetails/")#=Id#">#=ShipmentNumber#</a>'
                }, {
                    field: "OrderNumber",
                    title: "@T("Admin.Orders.Shipments.OrderID")",
                    width: 100,
                    template: '<a class="k-link" href="@Url.Content("~/Admin/Order/Edit/")#=OrderId#">#=OrderNumber#</a>'
                }, {
                    field: "TrackingNumber",
                    title: "@T("Admin.Orders.Shipments.TrackingNumber")",
                    width: 100,
                    template: '<a class="k-link" href="@Url.Content("~/Admin/Shipment/ShipmentDetails/")#=Id#">#=kendo.htmlEncode(TrackingNumber)#</a>'
                }, {
                    field: "TotalWeight",
                    title: "@T("Admin.Orders.Shipments.TotalWeight")",
                    width: 80,
                    minScreenWidth: 770,
                }, {
                    field: "ShippedDate",
                    title: "@T("Admin.Orders.Shipments.ShippedDate")",
                    width: 180,
                    type: "date",
                    format: "{0:G}"
                }, {
                    field: "DeliveryDate",
                    title: "@T("Admin.Orders.Shipments.DeliveryDate")",
                    width: 180,
                    type: "date",
                    format: "{0:G}"
                }]
            });
        });

        //details grid
        function detailInit(e) {
            $("<div/>").appendTo(e.detailCell).kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                            url: "@Html.Raw(Url.Action("ShipmentsItemsByShipmentId", "Shipment"))?shipmentId="+e.data.Id,
                            type: "POST",
                            dataType: "json",
                            data: addAntiForgeryToken
                        }
                    },
                    schema: {
                        data: "Data",
                        total: "Total",
                        errors: "Errors"
                    },
                    error: function(e) {
                        display_kendoui_grid_error(e);
                        // Cancel the changes
                        this.cancelChanges();
                    },
                    serverPaging: true,
                    serverFiltering: true,
                    serverSorting: true
                },
                scrollable: false,
                sortable: true,
                pageable: {
                    refresh: true,
                    numeric: false,
                    previousNext: false,
                    info: false
                },
                columns: [
                    {
                        field: "ProductName",
                        title: "@T("Admin.Orders.Shipments.Products.ProductName")",
                        width: 400
                    },{
                        field: "ShippedFromWarehouse",
                        title: "@T("Admin.Orders.Shipments.Products.Warehouse")",
                        width: 150
                    },{
                        field: "QuantityInThisShipment",
                        title: "@T("Admin.Orders.Shipments.Products.QtyShipped")",
                        width: 150
                    },{
                        field: "ItemWeight",
                        title: "@T("Admin.Orders.Shipments.Products.ItemWeight")",
                        width: 150
                    },{
                        field: "ItemDimensions",
                        title: "@T("Admin.Orders.Shipments.Products.ItemDimensions")",
                        width: 150
                    }
                ]
            });
        }
    </script>


    <script type="text/javascript">

        var selectedIds = [];

        $(document).ready(function () {

            //load states when changing a country dropdownlist
            $("#@Html.FieldIdFor(model => model.CountryId)").change(function () {
                var selectedItem = $(this).val();
                var ddlStates = $("#@Html.FieldIdFor(model => model.StateProvinceId)");
                $.ajax({
                    cache: false,
                    type: "GET",
                    url: "@(Url.Action("GetStatesByCountryId", "Home"))",
                    data: { "countryId": selectedItem, "addAsterisk": "true" },
                    success: function (data) {
                        ddlStates.html('');
                        $.each(data, function (id, option) {
                            ddlStates.append($('<option></option>').val(option.id).html(option.name));
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve states.');
                    }
                });
            });

            $("#@Html.FieldIdFor(model => model.TrackingNumber)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#search-shipments").click();
                    return false;
                }
            });
            $("#@Html.FieldIdFor(model => model.City)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#search-shipments").click();
                    return false;
                }
            });

            //search button
            $('#search-shipments').click(function () {
                //search
                var grid = $('#shipments-grid').data('kendoGrid');
                grid.dataSource.page(1); //new search. Set page size to 1
                //grid.dataSource.read(); we already loaded the grid above using "page" function
                //clear selected checkboxes
                $('.checkboxGroups').prop('checked', false).change();
                selectedIds = [];
                return false;
            });


            //"ship selected" button
            $('#ship-selected').click(function(e) {
                e.preventDefault();

                var postData = {
                    selectedIds: selectedIds
                };
                addAntiForgeryToken(postData);

                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "@(Url.Action("SetAsShippedSelected", "Shipment"))",
                    data: postData,
                    complete: function(data) {
                        //reload grid
                        var grid = $('#shipments-grid').data('kendoGrid');
                        grid.dataSource.read();
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                    },
                    traditional: true
                });
                return false;
            });

            //"deliver selected" button
            $('#deliver-selected').click(function(e) {
                e.preventDefault();

                var postData = {
                    selectedIds: selectedIds
                };
                addAntiForgeryToken(postData);

                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "@(Url.Action("SetAsDeliveredSelected", "Shipment"))",
                    data: postData,
                    complete: function(data) {
                        //reload grid
                        var grid = $('#shipments-grid').data('kendoGrid');
                        grid.dataSource.read();
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                    },
                    traditional: true
                });
                return false;
            });


            $('#mastercheckbox').click(function () {
                $('.checkboxGroups').prop('checked', $(this).is(':checked')).change();
            });

            //wire up checkboxes.
            $('#shipments-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function (e) {
                var $check = $(this);
                if ($check.is(":checked") == true) {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked == -1) {
                        //add id to selectedIds.
                        selectedIds.push($check.val());
                    }
                }
                else {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked > -1) {
                        //remove id from selectedIds.
                        selectedIds = $.grep(selectedIds, function (item, index) {
                            return item != $check.val();
                        });
                    }
                }
                updateMasterCheckbox();
            });
        });

        function additionalData() {
            var data = {
                StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
                EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
                TrackingNumber: $('#@Html.FieldIdFor(model => model.TrackingNumber)').val(),
                CountryId: $('#@Html.FieldIdFor(model => model.CountryId)').val(),
                StateProvinceId: $('#@Html.FieldIdFor(model => model.StateProvinceId)').val(),
                City: $('#@Html.FieldIdFor(model => model.City)').val(),
                WarehouseId: $('#@Html.FieldIdFor(model => model.WarehouseId)').val(),
                LoadNotShipped: $('#@Html.FieldIdFor(model => model.LoadNotShipped)').is(':checked')
            };
            addAntiForgeryToken(data);
            return data;
        }

        function onDataBound(e) {
            $('#shipments-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
                var currentId = $(this).val();
                var checked = jQuery.inArray(currentId, selectedIds);
                //set checked based on if current checkbox's value is in selectedIds.
                $(this).prop('checked', checked > -1);
            });

            updateMasterCheckbox();
        }

        function updateMasterCheckbox() {
            var numChkBoxes = $('#shipments-grid input[type=checkbox][id!=mastercheckbox]').length;
            var numChkBoxesChecked = $('#shipments-grid input[type=checkbox][id!=mastercheckbox]:checked').length;
            $('#mastercheckbox').prop('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
        }
    </script>

</form>
@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
<form asp-controller="Shipment" asp-action="PdfPackagingSlipSelected" method="post" id="pdf-packaging-slip-selected-form">
    
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
</form>

<script type="text/javascript">

    $(document).ready(function () {
        $('#exportpackagingslips-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#pdf-packaging-slip-selected-form #selectedIds').val(ids);
            $('#pdf-packaging-slip-selected-form').submit();
            return false;
        });
    });

</script>
